import { defineStore } from "pinia";
import { Icon } from "@iconify/vue";
import { authApi, sysUserApi } from "@/api";
import { views } from "@/views";
import { BasicLayout, BlankLayout } from "@/layouts";
import { isString } from "@/utils";
import { useTabStore } from "../..";

export const useRouteStore = defineStore("router-store", () => {
  /** 动态权限路由 */
  const permsRoutes = ref<AuthRoute.Route[]>([]);

  /** 保持keepalive的路由（组件名） */
  const keepAliveRoutes = ref<string[]>([]);

  /** 菜单数据 */
  const menus = computed(() => route2Menu(permsRoutes.value) || []);

  /** 获取动态路由 */
  const getPermsRoutes = async () => {
    try {
      const { data } = await sysUserApi.getRoute();
      permsRoutes.value = data;
    } catch (_err) {
      permsRoutes.value = [];
    }
    routeMapping(permsRoutes.value);
    // 初始化首页的tab
    useTabStore().initHomeTab(permsRoutes.value);
    return permsRoutes.value;
  };

  const getKeepAliveRoutes = async () => {
    const { data } = await authApi.getKeepAliveRoute();
    keepAliveRoutes.value = data;
    return data;
  };

  return {
    permsRoutes,
    keepAliveRoutes,
    menus,
    getPermsRoutes,
    getKeepAliveRoutes
  };
});

/** 映射路由到对应的组件 */
let counter = 0;
const routeMapping = (routes?: AuthRoute.Route[]) => {
  if (!routes || !routes.length) return;

  for (let i = 0; i < routes.length; i++) {
    const route = routes[i];
    if (route.meta?.type == 0) {
      route.component = route.meta?.isRoot ? BasicLayout : BlankLayout;
      route.path = "/catalog" + counter++;
    } else if (isString(route.component)) {
      route.meta!.componentName = route.component as string;
      route.component = views[route.meta!.componentName];
      if (!route.component) {
        console.error("未能找到对应组件：", route.meta!.componentName);
        routes.splice(i, 1);
        i--;
        continue;
      }
    }
    routeMapping(route.children);
  }
};

/** 路由转化为菜单 */
const route2Menu = (
  routes?: AuthRoute.Route[]
): App.GlobalMenuOption[] | undefined => {
  if (!routes || !routes.length) return;

  return routes
    .filter((route) => !route.meta?.hide)
    .map((route) => {
      return {
        label: route.meta!.title!,
        key: route.name,
        path: route.path,
        newTab: route.meta!.newTab!,
        icon: () => <Icon icon={route.meta!.icon!}></Icon>,
        children: route2Menu(route.children),
      };
    });
};
